import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // process.env.NODE_ENV === "development"
  //   ? process.env.VUE_APP_BASE_API
  //   : // : `http://127.0.0.1:9980`,
  //     "",
  timeout: 15000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      if (response.status == 401) {
        MessageBox.confirm("无此权限，请刷新页面", "系统提示", {
          confirmButtonText: "刷新页面",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          location.reload();
        });
      } else {
        return Promise.reject(new Error(res.message || "Error"));
      }
    } else {
      return res;
    }
  },
  error => {
    Message({
      message: `${response.request.responseURL} ${error.message}`,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
